package com.example.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.product.entity.ProductEntity;
import com.example.product.mapper.ProductMapper;
import com.example.product.feign.param.Price;
import com.example.product.service.IProductService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;


@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductEntity> implements IProductService {

    @Override
    public Integer money(List<Price> prices) {
        int allPrice = 0;

        for (Price price : prices) {
            ProductEntity productEntity = this.baseMapper.selectById(price.getProductId());
            if (productEntity == null) {
                continue;
            }
            allPrice = allPrice + (productEntity.getPrice() * price.getCount());

        }
        return allPrice;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean lockStock(Price price) {

        LambdaQueryWrapper<ProductEntity> lqw = new LambdaQueryWrapper<ProductEntity>()
                .eq(ProductEntity::getId,price.getProductId())
                .last("for update");

        ProductEntity productEntity = this.baseMapper.selectOne(lqw);
        if(productEntity.getLockStock() + price.getCount() <= productEntity.getStock()){
            this.baseMapper.updateLockStock(price.getProductId(),price.getCount());
            return true;
        }
        return false;
    }
}
